package com.wenwei.net;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * Created by Administrator on 2016/9/2.
 *
 * 抽象base subscriber ，对请求开始以及完成统一处理
 */
public abstract class BaseSubscriber<T> extends Subscriber<T>{

    private boolean isShowProgressDialog;//是否需要显示加载进度条
    private String showMsg;//加载信息
    private ProgressDialog dialog;
    private Context mContext;

    /**
     *
     * @param context 上下文对象
     * @param b 是否显示progressdialog
     * @param msg dialog显示文字
     */
    public BaseSubscriber(Context context,boolean b,String msg){
        this.mContext = context;
        this.isShowProgressDialog = b;
        this.showMsg = msg;
    }

    public BaseSubscriber(Context context){
        this.mContext = context;
        this.isShowProgressDialog = false;
        this.showMsg = "";
    }

    @Override
    public void onStart() {
        super.onStart();
        //首先判断是否有网络
        if (!NetworkUtil.isNetworkAvailable(mContext)) {
            Toast.makeText(mContext, "当前无网路，请检查你的网络连接是否正常", Toast.LENGTH_SHORT).show();
            onCompleted();
        }
        //显示progressdialog
        try {
            if(isShowProgressDialog){
                dialog = new ProgressDialog(mContext);
                dialog.setMessage(showMsg);
                dialog.show();
            }
        }catch (Exception e){
            Logger.d("异常捕捉："+e.toString());
        }

    }

    @Override
    public void onCompleted() {
        try {
            if(isShowProgressDialog){
                if(dialog!=null){
                    dialog.dismiss();
                }
            }
        }catch (Exception e){
            Logger.d("异常捕捉："+e.toString());
        }

    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            Toast.makeText(mContext, "网络超时，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else if (e instanceof ConnectException) {
            Toast.makeText(mContext, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else if (e instanceof ApiException){
            Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
            Logger.d("请求错误:"+e.getMessage());
        }else {
            Logger.d(e.getMessage());
        }
        if(isShowProgressDialog){
            dialog.dismiss();
        }
    }


    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    public abstract void onSuccess(T t);
}
